﻿using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Jade.Tools.SL.Controls.LoadingControl;

namespace MediaBrowserSL.RIA.Converters
{
    /// <summary>
    /// String to Image Converter
    /// </summary>
    public class StringToImageLoaderConverter : IValueConverter
    {
        private String perviousUrlImg;
        private ImageLoader loader;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            String urlImg = value as String;
            try
            {
                if (!String.IsNullOrEmpty(urlImg))
                {
                    if (!urlImg.Equals(perviousUrlImg))
                    {
                        loader = new ImageLoader();
                        Uri uri = new Uri(urlImg, UriKind.RelativeOrAbsolute);
                        BitmapImage b = new BitmapImage(uri);
                        loader.Source = b;
                        perviousUrlImg = urlImg;
                    }
                    return loader;
                }
                else
                {
                    return new Image();
                }

            }
            catch (Exception)
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Image img = value as Image;
            return img.Source.ToString();
        }
    }
}
